//
//  StrategyCollectionViewController.m
//  Preject_B
//
//  Created by lanou on 15/12/16.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "StrategyCollectionViewController.h"
#import "LORequestManger.h"
#import "StrategyModel.h"
#import "StrategyCollectionViewCell.h"
#import "StrategyCollectionReusableView.h"
#import "SpecialCollectionReusableView.h"
#import "MainClassTableViewController.h"
#import "SpecialModel.h"
#import "MoreTableViewController.h"
@interface StrategyCollectionViewController ()<UICollectionViewDelegateFlowLayout>
@property (nonatomic, retain)NSMutableArray *keyArray;
@property (nonatomic, retain)NSMutableDictionary *modelDic;
@property (nonatomic, retain)NSMutableArray *SpecialArray;

@end

@implementation StrategyCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerClass:[StrategyCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self setflowLayout];
    [self setdata];
    [self setSpecialData];
    
    [self.collectionView registerClass:[StrategyCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];
    [self.collectionView registerClass:[SpecialCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader"];
    
}


- (void)setflowLayout
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    flowLayout.itemSize = CGSizeMake(kWidth / 4.0 - 20, 90);
    //    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
}


- (void)setSpecialData
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *savedEncodedData = [defaults objectForKey:@"SpecialArray"];
    
    if (savedEncodedData != nil) {
        _SpecialArray = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:savedEncodedData];
    }else
    
    [LORequestManger GET:kStrategySpecial success:^(id response) {
        _SpecialArray = [NSMutableArray array];
        NSDictionary *rootDic = (NSDictionary *)response;
        
        NSArray *rootArr = rootDic[@"data"][@"collections"];
        for (NSDictionary *dic in rootArr) {
            SpecialModel *model = [[SpecialModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            model.imageIcon = [self imageWithUrl:model.banner_image_url];
            [_SpecialArray addObject:model];
        }
        
        if (savedEncodedData == nil) {
            [self.collectionView reloadData];
        }
        
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_SpecialArray];
        [defaults setObject:data forKey:@"SpecialArray"];
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}



- (void)setdata
{
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *savedEncodedData = [defaults objectForKey:@"StrategyModelDic"];
    NSData *savedEncodedData2 = [defaults objectForKey:@"StrategyKeyArray"];
    
    
    if (savedEncodedData != nil) {
        _modelDic = (NSMutableDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:savedEncodedData];
        _keyArray = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:savedEncodedData2];
        return;
    }else
    {
    [LORequestManger GET:kStrategyAll success:^(id response) {
        _modelDic = [NSMutableDictionary dictionary];
        _keyArray = [NSMutableArray array];
        NSDictionary *rootDic = (NSDictionary *)response;
        //        NSLog(@"%@",rootDic);
        NSArray *rootArr = rootDic[@"data"][@"channel_groups"];
        for (NSDictionary *dic in rootArr) {
            NSMutableArray *modelArray = [NSMutableArray array];
            [_keyArray addObject:dic[@"name"]];
            for (NSDictionary *dic2 in dic[@"channels"]) {
                StrategyModel *model = [[StrategyModel alloc] init];
                [model setValuesForKeysWithDictionary:dic2];
                model.imageIcon = [self imageWithUrl:model.icon_url];
                [modelArray addObject:model];
            }
            [_modelDic setObject:modelArray forKey:dic[@"name"]];
            
            if (_keyArray.count < 3) {
                [self.collectionView reloadData];
            }
        }
       
        if (savedEncodedData == nil) {
            [self.collectionView reloadData];
        }
        
        
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_modelDic];
        [defaults setObject:data forKey:@"StrategyModelDic"];
        
        NSData *data2 = [NSKeyedArchiver archivedDataWithRootObject:_keyArray];
        [defaults setObject:data2 forKey:@"StrategyKeyArray"];
        
        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    }
}

- (UIImage *)imageWithUrl:(NSString *)urlStr
{
    NSURL *url = [NSURL URLWithString:urlStr];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    return image;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _keyArray.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_modelDic[_keyArray[section]] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    StrategyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.model = _modelDic[_keyArray[indexPath.section]][indexPath.row];
    
    // Configure the cell
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MainClassTableViewController *mainClassTVC = [[MainClassTableViewController alloc] init];
    mainClassTVC.ID = [_modelDic[_keyArray[indexPath.section]][indexPath.row] ID];
    
    [mainClassTVC setHidesBottomBarWhenPushed:YES];
    mainClassTVC.navigationItem.title = [_modelDic[_keyArray[indexPath.section]][indexPath.row] name];
    [self.navigationController pushViewController:mainClassTVC animated:YES];
}



#pragma mark 区头相关

// 通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        SpecialCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader" forIndexPath:indexPath];
        
        headerView.modelArray = _SpecialArray;
        headerView.title = _keyArray[indexPath.section];
        [headerView.collectionView reloadData];
        
        headerView.myBlock = ^(MainClassTableViewController *mainClassTVC) { // 用Block 实现从后往前传值
            [self.navigationController pushViewController:mainClassTVC animated:YES];
        };
        
        [headerView.specialMoreButton addTarget:self action:@selector(SpecialMore) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        return headerView;
        
    }else
    {
        StrategyCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];

        headerView.title = _keyArray[indexPath.section];
        
        return headerView;
        
    }
}




// header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(0, 160);
    }else
    {
        return CGSizeMake(0, 30);
    }
    
}



// 更多专题按钮事件

- (void)SpecialMore
{
    MoreTableViewController *moreTVC = [[MoreTableViewController alloc] init];
    [moreTVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:moreTVC animated:YES];
    moreTVC.myBlock = ^(MainClassTableViewController *mainClassTVC) { // 用Block 实现从后往前传值
        
        [self.navigationController pushViewController:mainClassTVC animated:YES];
    };
}





@end
